'use strict'

let http = require('http')
let fs = require('fs')
let path = require('path')


let port = 5777

http.createServer((req, res) => {
    let pathname = req.url;
    console.log(pathname);
    let currentpath = __dirname;
    console.log(currentpath); //当前文件的上级目录
    let fullpath = path.join(currentpath, pathname);
    console.log(fullpath);
    let filepath = getFiles(fullpath);

    if (filepath !== '404') {
        fs.createReadStream(filepath).pipe(res)
    } else {
        res.writeHead(404)
        res.end('404 not found')
    }

}).listen(port)

function getFiles(pointPath) {
    let filepath = '404'
    if (fs.existsSync(pointPath)) {
        let stat = fs.statSync(pointPath)
        if (stat.isFile()) {
            filepath = pointPath;
        } else {
            let files = fs.readdirSync(pointPath)
            files.forEach(item => {
                let tmpPath = path.join(pointPath, item)
                let tmpStat = fs.statSync(tmpPath)
                if (tmpStat.isFile()) {
                    filepath = tmpPath;
                    return;
                }
            })
        }
    }

    return filepath;
}

function message() {
    console.log(`Server is running at http://127.0.0.1:${port}`);
}

message()